package main

import (
	"encoding/binary"
	"flag"
	"fmt"

	"gitee.com/thubcc/mobile/fm"
	"gitee.com/thubcc/mobile/utils"
	"gitee.com/thubcc/rtlmmap"
	"github.com/hajimehoshi/oto"
	"github.com/prometheus/common/log"
	"gopkg.in/hraban/opus.v2"
)

var (
	argPort = flag.Int("p", 0, "Rx antana port")
	argFc   = flag.Float64("f", 97.6e6, "FM Freqency")
	argGain = flag.Float64("g", 40.0, "Rx Gain")
)

func initDev() {
	var dev = rtlmmap.NewDevice(*argPort)
	dev.Open()
	dev.SetFrequency(int(*argFc))
	dev.SetSampleRate(1920000)
	dev.SetGain(int(*argGain * 10.))
	dev.Start()
}

func initView() utils.RFInterface {
	config := rtlmmap.DefaultFMConfig
	config.SetCenterFrequency(*argFc)
	log.Info("config", config)
	view := rtlmmap.NewRtlView(*argPort, config)
	ftco := view.FTV(*argPort)
	return ftco
}

type Player struct {
	dec    *opus.Decoder
	buf    []int16
	player *oto.Player
}

func NewPlayer(ctx *oto.Context) *Player {
	const sampleRate = 48000
	const channels = 2
	dec, err := opus.NewDecoder(sampleRate, channels)
	if err != nil {
		log.Error(err)
		return nil
	}
	player := ctx.NewPlayer()
	frameSize := channels * 120 * sampleRate / 1000
	buf := make([]int16, int(frameSize))
	return &Player{dec, buf, player}
}

func (player *Player) Write(din []byte) (int, error) {
	n, err := player.dec.Decode(din, player.buf)
	if err != nil {
		return 0, err
	}
	err = binary.Write(player.player, binary.LittleEndian, player.buf[:n*2])
	if err != nil {
		return 0, err
	}
	log.Info("package ", len(din), n)
	return len(din), nil
}
func (player *Player) Close() error { return nil }
func main() {
	flag.Parse()
	initDev()
	inf := initView()
	fm := fm.NewFM(200./1920., 4, inf)
	otoc, err := oto.NewContext(48000, 2, 2, 960*50)
	if err != nil {
		fmt.Println(err)
	}
	play := NewPlayer(otoc)
	fm.StartWithOpus(play)
	// play := otoc.NewPlayer()
	// fm.Start(play)
}
